package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements cn.itcast.hotel.service.IHotelService {
    @Autowired
    private RestHighLevelClient client;


    @Override
    public PageResult search(RequestParams params) throws IOException {
        //1准备请求
        SearchRequest request = new SearchRequest("hotel");
        //2.准备DSL语句
        //2.1query
        //构建booleanQuery
        BoolQueryBuilder boolQuery = getBasicBoolQueryBuilder(params);
        request.source().query(boolQuery);

        //2.2分页
        int page = params.getPage();
        int size = params.getSize();
        request.source().from((page - 1) * size).size(size);
        //2.3排序
        String location = params.getLocation();
        if (location != null && !"".equals(location)){
            request.source().sort(SortBuilders
                    .geoDistanceSort("location",new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS)
            );

        }
        //3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4.解析请求
        return extracted(response);

    }

    /**
     * 返回聚合信息
     * @return
     * @param params
     */
    @Override
    public Map<String, List<String>> filters(RequestParams params) throws IOException {
        //1.准备请求
        SearchRequest request = new SearchRequest("hotel");
        //2.发送请求
        //查询信息，query
        BoolQueryBuilder boolQuery = getBasicBoolQueryBuilder(params);
        request.source().query(boolQuery);
        //2.1设置文档
        request.source().size(0);
        //2.2设置聚合
        buildAggregation(request);
        //3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4.解析结果
        HashMap<String, List<String>> result = new HashMap<>();
        Aggregations aggregations = response.getAggregations();
        //4.1根据品牌名称，获取品牌结果，并放入map中
        List<String> brandList = getAggByName(aggregations,"brandAgg");
        result.put("品牌",brandList);
        //4.1根据城市名称，获取城市结果，并放入map中
        List<String> cityAgg = getAggByName(aggregations,"cityAgg");
        result.put("城市",cityAgg);
        //4.1根据星级名称，获取星级结果，并放入map中
        List<String> starNameAgg = getAggByName(aggregations,"starNameAgg");
        result.put("星级",starNameAgg);
        return result;
    }

    /**
     * 实现自动补全
     * @param prefix
     * @return
     */
    @Override
    public List<String> getSuggestions(String prefix) throws IOException {
        //1.准备请求
        SearchRequest request = new SearchRequest("hotel");
        //2.DSL语句
        request.source().suggest(new SuggestBuilder()
                .addSuggestion("mysuggestion", SuggestBuilders
                        .completionSuggestion("suggestion")
                        .prefix(prefix)
                        .skipDuplicates(true)
                        .size(10)
                ));
        //3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4.解析结果
        //4.1获取suggest
        Suggest suggest = response.getSuggest();
        //4.2获取suggest名称
        CompletionSuggestion mysuggestion = suggest.getSuggestion("mysuggestion");
        //4.3获取options
        List<CompletionSuggestion.Entry.Option> options = mysuggestion.getOptions();
        //4.4遍历option
        List<String> list = new ArrayList<>(options.size());
        for (CompletionSuggestion.Entry.Option option : options) {
            String text = option.getText().toString();
            list.add(text);
        }
        return list;
    }

    @Override
    public void saveById(Long hotelId) throws IOException {
        //查询酒店数据
        Hotel hotel = getById(hotelId);
        //转换为文档类型
        HotelDoc hotelDoc = new HotelDoc(hotel);
        //1.创建请求
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        //2.添加json
        request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
        //3.发送请求
        client.index(request,RequestOptions.DEFAULT);
    }

    @Override
    public void deleteById(Long hotelId) throws IOException {
        //准备请求
        DeleteRequest request = new DeleteRequest("hotel", hotelId.toString());
        //发送请求
        client.delete(request,RequestOptions.DEFAULT);
        System.out.println("删除索引");
    }

    private List<String> getAggByName(Aggregations aggregations,String aggName) {
        //4.1根据聚合名称得到聚合结果
        Terms brandTerms = aggregations.get(aggName);
        //4.2获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        //4.3遍历buckets
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            //获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("starNameAgg")
                .field("starName")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
    }

    private BoolQueryBuilder getBasicBoolQueryBuilder(RequestParams params) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字搜索，用must
        // 获取key
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        //条件过滤，filter
        //1.城市条件
        if (params.getCity() != null && !"".equals(params.getCity())){
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        //2.品牌条件
        if (params.getBrand() != null && !"".equals(params.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //3.星级条件
        if (params.getStarName() != null && !"".equals(params.getStarName())){
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        //价格范围
        if (params.getMaxPrice() != null && params.getMinPrice() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice()));
        }
        //算分控制
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                //原始查询，做相关性算分查询
                boolQuery,
                //function score 数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //其中的一个具体function score 元素
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                        //过滤条件
                        QueryBuilders.termQuery("isAD",true),
                        //算分函数
                        ScoreFunctionBuilders.weightFactorFunction(10)
                )
                });
        return boolQuery;
    }


    private PageResult extracted(SearchResponse response) {
        //4.解析结果
        SearchHits searchHits = response.getHits();
        //4.1得到总条数
        Long total = searchHits.getTotalHits().value;
        //4.2文档数组
        SearchHit[] hits = searchHits.getHits();
        //4.3遍历
        List<HotelDoc> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            //获取文档source
            String json = hit.getSourceAsString();
            //反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //排序
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length >0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            //添加数据
            list.add(hotelDoc);
            //获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            //判断
            if (!CollectionUtils.isEmpty(highlightFields)) {
                //根据name获取高亮结果
                HighlightField field = highlightFields.get("name");
                if (field != null) {
                    //获取高亮结果
                    String name = field.getFragments()[0].string();
                    //覆盖高亮结果
                    hotelDoc.setName(name);
                }
            }

        }
        //封装返回
        return new PageResult(total,list);
    }
}
